const app = getApp()

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
    bluetoothEnabled:false,
    canWrite:false,
    latitude:0,
    longitude:0,
    isLock:false,
    loading:false
  },
  openBluetoothAdapter() {//初始化蓝牙模块
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()//搜索蓝牙
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {//获取蓝牙适配器状态
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {//开始搜索附近的蓝牙设备
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()//寻找新设备
      },
    })
  },
  stopBluetoothDevicesDiscovery() {//停止搜寻附近的蓝牙设备
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {//监听寻找到新设备的事件
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  createBLEConnection(e) {//连接低功耗蓝牙设备
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    this.setData({
      deviceCode:name,
      loading:true
    })
    this.queryScope()
    wx.setStorageSync('deviceId', ds.deviceId)
    wx.setStorageSync('name', ds.name)
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
          loading:false
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {//断开与低功耗蓝牙设备的连接
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {//获取蓝牙设备所有服务(
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {//获取蓝牙设备某个服务中所有特征值
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              success(res){
                console.log('readBLECharacteristicValue:', res.errCode)
              }
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  writeBLECharacteristicValue() {//向低功耗蓝牙设备特征值中写入二进制数据
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._deviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  closeBluetoothAdapter() {//关闭蓝牙模块
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
  getLocation() {//获取位置信息
    wx.getLocation({
      type: 'wgs84',
      success:(res) => {
        // const latitude = res.latitude
        // const longitude = res.longitude
        // const speed = res.speed
        // const accuracy = res.accuracy
        // console.log(latitude)
        // console.log(longitude)
        this.setData({
            latitude:res.latitude,
            longitude:res.longitude
        })
      }
    })
  },
  queryScope(){//查询是否在范围内
    wx.request({
      // url: `http://www.yingliyun.com/v999/sys-marketing/login/findNearbyDeviceCode?longitude=${this.data.latitude}&latitude=${this.data.longitude}&deviceCode=${this.data.deviceCode}`,
      url: `http://www.yingliyun.com/v999/sys-marketing/login/findNearbyDeviceCode?longitude=11.1&latitude=22.2&deviceCode=110232`,
      success:(res)=>{
        // console.log(res.data.code);
        res.data.code === 0 ? this.setData({isLock:true}) : this.setData({isLock:false})
      }
    })
  },
  getSystem(){//获取系统信息
    console.log(1);
    wx.getSystemInfo({
        success:(res)=>{
          console.log(res);
          this.setData({
            bluetoothEnabled:res.bluetoothEnabled
          })
          if(!res.bluetoothEnabled){
            wx.showToast({
              title: '请打开蓝牙',
              icon:'none'
            }) 
          }
        }  
    })
  },

  autoLink(){//自动连接
    let deviceId = wx.getStorageSync('deviceId') || ''
    let name = wx.getStorageSync('name') || ''
    this.setData({
      deviceCode:name
    })
    if(deviceId){
      this.queryScope()
      wx.createBLEConnection({
        deviceId,
        success: (res) => {
          this.setData({
            connected: true,
            name,
            deviceId,
          })
          this.getBLEDeviceServices(deviceId)
        }
      })
      this.stopBluetoothDevicesDiscovery()
    }
  },

  onBLEConnectionStateChange(){//监听蓝牙连接状态改变的事件
    // wx.onBLEConnectionStateChange(deviceId,connected){
      
    // }
  },
  onLoad:async function () {
    await this.getSystem()
    await this.getLocation()
    if(this.data.bluetoothEnabled){
      await this.openBluetoothAdapter()
      await this.autoLink()
      console.log(this.data.canWrite);
      setTimeout(function(){
        wx.stopBluetoothDevicesDiscovery()
      }, 6000);
    }
  },
  onUnload: function () {
    wx.stopBluetoothDevicesDiscovery()
    this.closeBLEConnection()
    this.closeBluetoothAdapter()
  },
})


